package com.lagou.minicat.servlet;

import com.lagou.minicat.mapper.MappingData;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName Request
 * @Description
 * @Author playboy
 * @Date 2021/5/22 11:58 上午
 * @Version 1.0
 **/
public class Request {

	/**
	 * 请求的输入流
	 */
	private InputStream inputStream;

	private Method method;

	private String url;

	private String host;

	private MappingData mappingData;

	/**
	 * 是否是动态资源
	 */
	private boolean dynamic = true;

	public Request(InputStream inputStream) {
		this.inputStream = inputStream;
		try {
			int count = 0;
			while (count == 0) {
				count = inputStream.available();
			}
			byte[] bytes = new byte[count];
			inputStream.read(bytes);
			//s的内容
			//GET /demo1/abc HTTP/1.1
			//Host: localhost:8080
			String s = new String(bytes, StandardCharsets.UTF_8);
			String[] requestHeaders = s.split("\r");
			//GET /demo1/abc HTTP/1.1
			String first = requestHeaders[0];
			String[] s1 = first.split(" ");
			if (s1[0].equals("GET")) {
				method = Method.GET;
			} else {
				method = Method.POST;
			}
			url = s1[1];
			//requestHeaders[1]   Host: localhost:8080
			host = requestHeaders[1].split(" ")[1].split(":")[0];
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public Method getMethod() {
		return method;
	}

	public String getUrl() {
		return url;
	}

	public String getHost() {
		return host;
	}

	public Servlet getServlet() {
		return mappingData.getWrapper().getServlet();
	}

	public void setMappingData(MappingData mappingData) {
		this.mappingData = mappingData;
	}

	public MappingData getMappingData() {
		return mappingData;
	}

	public boolean isDynamic() {
		return dynamic;
	}

	public void setDynamic(boolean dynamic) {
		this.dynamic = dynamic;
	}

	static enum Method {
		GET("GET"),
		POST("POST");

		Method(String value) {
			this.value = value;
		}

		private String value;

		public String getValue() {
			return value;
		}
	}
}
